import services from '@/services/user';
import {
    ActionType,
    PageContainer,
    ProColumns,
    ProDescriptions,
    ProDescriptionsItemProps,
    ProFormSelect,
    ProTable,
} from '@ant-design/pro-components';
import {Button, Divider, Drawer, message, Modal, Tooltip} from 'antd';
import React, {useRef, useState} from 'react';
import CreateForm from './components/CreateForm';
import {useNavigate} from 'umi';
// import { history } from '@umijs/max';
const { userPage, adminRegister, deleteById } = services.UserController;



//  用户状态类型
type StatusConfigType = {
  [key: string]: { text: string; status: number; defaultTip?: string };
};
//  用户状态类型
const statusConfig: StatusConfigType = {
'1': { text: '正常', status: 1, defaultTip: '这是正常状态' },
'2': { text: '锁定', status: 2, defaultTip: '该用户已被锁定' },
'3': { text: '逻辑删除', status: 3, defaultTip: '该记录已被逻辑删除' },
};



/**
 * 添加用户
 * @param fields
 */
const userAdd = async (fields: API.UserAdd) => {
  const hide = message.loading('正在添加');
  try {
    await adminRegister({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};


/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (id: number) => {
  const hide = message.loading('正在删除');
  if (!id) return true;
  try {
    await deleteById(id);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC<unknown> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [row, setRow] = useState<API.UserVO>();
  const [selectedRowsState, setSelectedRows] = useState<API.UserVO[]>([]);
  const navigate = useNavigate();
  const [current, setCurrent] = useState(1); // 当前页码
  const [pageSize, setPageSize] = useState(10); // 每页显示条数


  const columns: ProColumns<API.UserVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      tooltip: '唯一的 key',
      hideInForm: true,
      hideInTable: true,
      search: false
    },
    {
      title: '登录名',
      dataIndex: 'loginName',
      tooltip: '唯一的 key',
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '名称为必填项',
          },
        ],
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '密码',
      dataIndex: 'password',
      valueType: 'text',
      hideInTable: true,
      search: false
      // 在列表中隐藏，新增中使用
    },
    {
      title: '性别',
      dataIndex: 'gender',
      valueType: 'select', // Ensuring the value type is 'select'
      valueEnum: {
        1: { text: '男', status: '1' },
        2: { text: '女', status: '2' },
        0: { text: '未知', status: '0' }
      },
      search: {
        transform: (value) => (value === '1' ? 1 : value === '2' ? 2 : 0), // Assuming the search transform is needed
      },
      // Default value for the form
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          // Apply default value only for the form, not search
          return (
              <ProFormSelect
                  {...rest}
                  valueEnum={{
                    1: '男',
                    2: '女',
                    0: '未知',
                  }}
                  fieldProps={{
                    defaultValue: '1', // Set default value to '男' (1)
                    placeholder: '请选择性别',
                  }}
              />
          );
        }
        return defaultRender(item);
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      search: false,
      render: (text: any, record: API.UserVO) => {
        const status = String(text); // 确保 text 是字符串
        const currentStatus = status in statusConfig ? statusConfig[status] : undefined;
        return (
          <Tooltip title={record.statusMark  || '没有提示信息'}>
               <span>{currentStatus?.text || text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
          <>
            <a
                onClick={() => {
                  const params = new URLSearchParams({
                    userName: record.name,
                  });
                  const url = `/user/manage/role/${record.id}?${params.toString()}`;
                  console.log('Navigating to:', url); // 添加这行
                  navigate(url);
                }}
            >
              角色
            </a>
            <Divider type="vertical"/>
            <a
                onClick={() => {
                  Modal.confirm({
                    title: '确认删除',
                    content: `确定要删除用户 ${record.name} 吗？`,
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: async () => {
                      const success = await handleRemove(record.id);
                      if (success) {
                        actionRef.current?.reloadAndRest?.();
                      }
                    },
                  });
                }}
            >
              删除
            </a>
          </>
      ),
    },
  ];
  return (
      <PageContainer
          header={{
            title: '',
          }}
      >
        <ProTable<API.UserVO>
            headerTitle="查询用户"
            actionRef={actionRef}
            rowKey="id"
            search={{
              labelWidth: 120,
            }}
            toolBarRender={() => [
              <Button
                  key="1"
                  type="primary"
                  onClick={() => handleModalVisible(true)}
              >
                新增
              </Button>,
            ]}
            pagination={{
              current, // 当前页码
              pageSize, // 每页条数
              showSizeChanger: true, // 是否可以改变 pageSize
          pageSizeOptions: ['5', '10', '20', '50'], // 自定义每页条数下拉选项
          onChange: (page, pageSize) => { // 页码或 pageSize 改变的回调。
            setCurrent(page);
            setPageSize(pageSize);
          },
          onShowSizeChange: (current, size) => {// pageSize 改变的回调。
            setCurrent(current);
            setPageSize(size);
          },
        }}
        // , sorter, filter
        request={async (params) => {
          const find: API.UserPage  = {
            name: params.name ? params.name : undefined,
            gender: params.gender ? params.gender : undefined,
            page : {
              pageIndex: params.current,
              pageSize: params.pageSize,
            },
          };
          const { data, success } = await userPage({
            ... find,
            // FIXME: remove @ts-ignore
            // @ts-ignore
            // sorter,
            // filter,
          });
          return {
              data: data?.rows || [],
              total: data?.total,
              pageSize: data?.pageSize,
              current: data?.currentPage,
              success,
          };
        }}
        columns={columns}
      />
      <CreateForm
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable<API.UserVO, API.UserVO>
          onSubmit={async (value) => {
            const success = await userAdd(value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          type="form"
          columns={columns}
        />
      </CreateForm>
      <Drawer
        width={600}
        open={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions<API.UserVO>
            column={2}
            title={row?.name}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.name,
            }}
            columns={columns as ProDescriptionsItemProps<API.UserVO>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
